<style lang="scss" scoped>
.status-3 {
  color: #07c160;
}

.cert-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: .24rem;
  color: #666;
  padding: .2rem 0;
}

.cert-submit {
  margin: 0 .2rem;
}
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar :title="title" left-arrow left-text="返回" @click-left="$router.back()" fixed />
    <div class="cert-auth-box">
      <template>
        <template v-if="isAuthed">
          <van-form ref="pzForm" input-align="right">
            <van-field readonly label="是否认证">
              <template #input>
                <div class="status-3">已认证</div>
              </template>
            </van-field>
            <van-field readonly label="所在城市" :value="form.cityName" />
            <van-field readonly label="身份证号" :value="form.idCard" :maxlength="18" />
          </van-form>

          <SingleUpload ref="idCardFront" :image.sync="form.hgPic1" :readonly="true" title="身份证正面"></SingleUpload>

          <SingleUpload ref="idCardBack" :image.sync="form.hgPic2" :readonly="true" title="身份证反面"></SingleUpload>
        </template>
        <template v-else>
          <van-form ref="phForm" input-align="right">
            <van-field clickable readonly name="city" label="所在城市" :value="form.cityName" placeholder="请选择"
              @click="showCitySelector" is-link />
            <van-field name="idCard" label="身份证号" v-model.trim="form.idCard" placeholder="请输入身份证号" />
          </van-form>
          <SingleUpload ref="idCardFront" :image.sync="form.hgPic1" :max-size="5"
            @handle-file="handleFile($event, 'hgFile1')" title="请上传身份证正面照片"></SingleUpload>
          <SingleUpload ref="idCardBack" :image.sync="form.hgPic2" :max-size="5"
            @handle-file="handleFile($event, 'hgFile2')" title="请上传身份证反面照片"></SingleUpload>
          <div class="cert-tips">
            您的证件号码我们只作认证使用，不作任何其他
            <br>
            用途，会为您绝对保密。
          </div>
          <div class="cert-submit">
            <van-button block type="default" color="#179AFE" @click="onSubmit">提交审核</van-button>
          </div>
        </template>
      </template>
    </div>

    <!-- 城市选择 -->
    <CascaderSelector :title="cascaderTitle" :key-name="cascaderKey" ref="CascaderSelector"
      @on-change="handleCascaderChange" @on-finish="handleCascaderFinish"></CascaderSelector>

    <Loading :isShow="loading"></Loading>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Loading from '@/components/Loading';
import CascaderSelector from '@/components/CascaderSelector';
import SingleUpload from '@/components/SingleUpload';
import { getProvinceList, getCityList, saveUserAuth, getUserAuth } from "../../api/user";
const fileUrl = process.env.VUE_APP_FILE_URL;

export default {
  name: 'CertAuth',
  components: {
    CascaderSelector,
    SingleUpload,
    Loading,
  },
  data() {
    return {
      loading: true,
      fileApi: fileUrl,
      id: null,
      title: '我的认证',
      form: {
        city: null,
        cityName: null,
        hgPic1: null,
        hgPic2: null,
        hgFile1: null,
        hgFile2: null,
        idCard: null,
      },
      cascaderKey: 'city',
      cascaderTitle: '请选择城市',
    };
  },
  mounted() {
    this.id = this.$route.params.id || null;
    this.title = '我的认证'
    this.getUserAuth();
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 是否已认证
    isAuthed() {
      return this.userInfo.user.authStatus === 3
    }
  },
  methods: {

    async showCitySelector() {
      const data = await this.getProvinceList();
      this.cascaderKey = 'city';
      this.cascaderTitle = '请选择城市';
      this.$refs.CascaderSelector.show(data);
    },

    // 城市
    async handleCascaderChange(data) {
      if (this.cascaderKey === 'city') {
        if (data.level === 0) {
          const citys = await this.getCityList(data.value);
          this.$refs.CascaderSelector.getDatas(data.value, citys);
        }
      }
    },

    async handleCascaderFinish(data) {
      let last = data[data.length - 1];
      if (this.cascaderKey === 'city') {
        this.form.cityName = last.text;
        this.form.city = last.value;
      }
    },

    async getProvinceList() {
      const { data } = await getProvinceList()
      return data.map(k => {
        return {
          text: k.name,
          value: k.id,
          children: []
        }
      })
    },

    async getCityList(provinceId, hasChild) {
      const { data } = await getCityList(provinceId)
      return data.map(k => {
        return hasChild ? {
          text: k.name,
          value: k.id,
          children: []
        } : {
          text: k.name,
          value: k.id
        }
      })
    },

    onSubmit() {
      this.$refs.phForm.validate().then(async () => {
        if (this.form.idCard.length !== 18) {
          return this.$toast('请输入18位正确的身份证号码')
        }
        if (!this.form.hgFile1) {
          return this.$toast('请上传身份证正面照')
        }
        if (!this.form.hgFile2) {
          return this.$toast('请上传工作证正面照')
        }
        let formData = new FormData();
        formData.append('idCard', this.form.idCard)
        formData.append('cityId', this.form.city)
        formData.append('cityName', this.form.cityName)
        formData.append('frontPic', this.form.hgFile1)
        formData.append('backPic', this.form.hgFile2)
        const { code, message } = await saveUserAuth(formData)
        if (code == 200) {
          let userInfo = JSON.parse(JSON.stringify(this.userInfo))
          userInfo.user.authStatus = 1;
          this.$store.commit('setUserInfo', userInfo);
          this.$toast('认证提交成功!')
        } else {
          this.$toast(message)
        }
      }, err => {
        if (err && err.length) {
          this.$toast(err[0].message)
        }
      })
    },

    async getUserAuth() {
      try {
        this.loading = true;
        const { code, message, data } = await getUserAuth();
        if (code == 200) {
          if (!!data) {
            this.form = {
              city: data.cityId,
              cityName: data.cityName,
              idCard: data.idCard
            }
            console.log(this.isAuthed);
            if (this.isAuthed) {
              this.form.hgPic1 = !!data.frontPic ? fileUrl + data.frontPic : '';
              this.form.hgPic2 = !!data.backPic ? fileUrl + data.backPic : '';
            }
            const that = this;
            if (!!data.frontPic) {
              this.form.hgPic1 = fileUrl + data.frontPic;
              this.getBase64(fileUrl + data.frontPic, (dataURL) => {
                that.form.hgFile1 = that.dataURLtoFile(dataURL, 'frontPic.jpg');
              })
            }
            if (!!data.backPic) {
              this.form.hgPic2 = fileUrl + data.backPic;
              this.getBase64(fileUrl + data.backPic, (dataURL) => {
                that.form.hgFile2 = that.dataURLtoFile(dataURL, 'backPic.jpg');
              })
            }
          }
        } else {
          this.$toast(message);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    },

    handleFile(file, keyName) {
      this.form[keyName] = file.file;
      if (keyName === 'hgFile1') {
        delete this.form.hgPic1;
        this.$set(this.form, 'hgPic1', file.content);
      }
      if (keyName === 'hgFile2') {
        delete this.form.hgPic2;
        this.$set(this.form, 'hgPic2', file.content);
      }
    },

    getBase64(url, callback) {
      let Img = new Image(), dataURL = '';
      Img.src = url + "?v=" + Math.random(); // 处理缓存,fix缓存bug,有缓存，浏览器会报错;
      Img.setAttribute("crossOrigin", 'Anonymous') // 解决控制台跨域报错的问题
      Img.onload = function () { //要先确保图片完整获取到，这是个异步事件
        var canvas = document.createElement("canvas"); //创建canvas元素
        var width = Img.width; //确保canvas的尺寸和图片一样
        var height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
        dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
        callback ? callback(dataURL) : null; //调用回调函数
      };
    },

    dataURLtoFile(dataurl, filename) {
      if (!dataurl) return;
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
};
</script>
